﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Collab.Common.Infrastructure
{
    public class Messenger : IObservable<IMessage>
    {
        private readonly Subject<IMessage> subject = new Subject<IMessage>();

        public IDisposable Subscribe(IObserver<IMessage> observer)
        {
            return this.subject.Subscribe(observer);
        }

        public void Send(IMessage message)
        {
            subject.OnNext(message);
        }

        public IObservable<T> OfType<T>() where T : class, IMessage
        {
            return this.Where(x => x is T).Select(x => x as T);
        }

        private static readonly Messenger defaultInstance = new Messenger();

        public static Messenger Default
        {
            get { return Messenger.defaultInstance; }
        }
    }
}
